﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
using System.Linq.Expressions;
using HHG.Common;

namespace OnLineExam.Web.mag.Handler
{
    /// <summary>
    /// PaperHandler 的摘要说明
    /// </summary>
    public class PaperHandler : IHttpHandler
    {
		private HttpContext _httpContext;
		private HttpRequest _httpRequest;
		private HttpResponse _httpResponse;
		private Data.OnlineExamEntities _ctx;
		private OnLineExam.Data.EfRepository<OnLineExam.Data.Paper> _paperRepository;
		private OnLineExam.Data.EfRepository<OnLineExam.Data.PaperInfo> _paperInfoRepository;

		public void ProcessRequest(HttpContext context)
        {
			_httpContext = context;
			_httpRequest = context.Request;
			_httpResponse = context.Response;
			_ctx = new Data.OnlineExamEntities();
			_paperRepository = new Data.EfRepository<Data.Paper>(_ctx);
			_paperInfoRepository = new Data.EfRepository<Data.PaperInfo>(_ctx);

			string type = context.Request.Params["type"];
            string hdType = context.Request.Form["hdType"];
            if (string.IsNullOrEmpty(type))
                type = "getlist";
       

            var ID = context.Request.QueryString["ID"].GetInt();

            OnLineExam.BLL.PaperManager bll = new OnLineExam.BLL.PaperManager();

            switch (type)
            {
                case "getlist":
                    #region 获取列表

                    int page = int.Parse(context.Request.Params["page"]);
                    int rows = int.Parse(context.Request.Params["rows"]);

                    

                    var depid = context.Request.Params["depid"].GetInt();
                    int startIndex = (page - 1) * rows + 1;
                    int endIndex = (page) * rows;


                    var query = _paperRepository.TableNoTracking.Where(s => s.DepID == depid);
                    int RecordCount = query.Count();

                   

                    var reItems = query.OrderBy(s => s.PaperID).Skip((page - 1) * rows).Take(rows).ToList();
                    

                    context.Response.Write(new DataGrid(RecordCount, reItems).SerializeObject());


					

                    #endregion
                    break;
                case "getlistForSelect":
					#region 获取下拉列表
					var list = _paperRepository.TableNoTracking;
                    var result= list.Select(s=>new { PaperID = s.PaperID, PaperName = s.PaperName}).ToList();
					WriteJson(result);

				WriteJson(result);
                    #endregion
                    break;
                case "edit":
                    #region 根据ID获取信息
                    var entity = _paperRepository.GetById(ID);
                    context.Response.Write(entity.SerializeObject()); 
                    #endregion
                    break;
                case "addsave":
                    #region 提交修改
                   
                     
                    var new_model = new Data.Paper();
                    
                    new_model.DepID = int.Parse(context.Request.Params["selectDep"]); ;
                    new_model.CourseID = int.Parse(context.Request.Params["selectCourse"]);
                    new_model.PaperName = context.Request.Params["txtPaperName"];
                    new_model.startExamTime = DateTime.Parse(context.Request.Params["txtStartDateTime"]);
                    new_model.EndExamTime = DateTime.Parse(context.Request.Params["txtEndDateTime"]);
                    new_model.ExamTime = context.Request.Params["txtExamTime"];
                    new_model.allowExamNum =int.Parse( context.Request.Params["txtallowExamNum"]);
                    new_model.passMark = int.Parse(context.Request.Params["txtpassmark"]);
                    new_model.joinemps = context.Request.Params["txtJoinEmpID"];
                    new_model.ProblemInfo = "单选:{0}:{1},多选:{2}:{3},判断:{4}:{5},填空:{6}:{7},问答:{8}:{9}";
                    new_model.ProblemInfo=string.Format(new_model.ProblemInfo,
                        context.Request.Params["txtSingleNum"], context.Request.Params["txtSingleFen"],
                        context.Request.Params["txtMultiNum"], context.Request.Params["txtMultiFen"],
                        context.Request.Params["txtJudgeNum"], context.Request.Params["txtJudgeFen"],
                        context.Request.Params["txtFillBlankNum"], context.Request.Params["txtFillBlankFen"],
                        context.Request.Params["txtQuestionNum"], context.Request.Params["txtQuestionFen"]
                        );

					//new_model.ProblemInfo = "0";

					using (var ctx=new Data.OnlineExamEntities())
					{ 
						new_model.PaperInfo=new_model.MarkInfo  ;

						ctx.Paper.Add(new_model);
						ctx.SaveChanges();

					}

                    context.Response.Write(1);//添加成功，返回ID,失败，返回0

                    #endregion
                    break;
                case "editsave":
                    #region 提交修改
                    var editId = context.Request.Form["hdID"].GetInt();
                    var o_model =_paperRepository.GetById(editId);
                    
                   
                    o_model.DepID = context.Request.Form["selectDep"].GetInt();
                    o_model.CourseID = context.Request.Form["selectCourse"].GetInt();
                    o_model.PaperName = context.Request.Params["txtPaperName"];
                    o_model.startExamTime = DateTime.Parse(context.Request.Params["txtStartDateTime"]);
                    o_model.EndExamTime = DateTime.Parse(context.Request.Params["txtEndDateTime"]);
                    o_model.ExamTime = context.Request.Params["txtExamTime"];
                    o_model.allowExamNum = int.Parse(context.Request.Params["txtallowExamNum"]);
                    o_model.passMark = int.Parse(context.Request.Params["txtpassmark"]);
                    o_model.joinemps = context.Request.Params["txtJoinEmpID"];
                    o_model.ProblemInfo = "单选:{0}:{1},多选:{2}:{3},判断:{4}:{5},填空:{6}:{7},问答:{8}:{9}";
                    o_model.ProblemInfo = string.Format(o_model.ProblemInfo,
                        context.Request.Params["txtSingleNum"], context.Request.Params["txtSingleFen"],
                        context.Request.Params["txtMultiNum"], context.Request.Params["txtMultiFen"],
                        context.Request.Params["txtJudgeNum"], context.Request.Params["txtJudgeFen"],
                        context.Request.Params["txtFillBlankNum"], context.Request.Params["txtFillBlankFen"],
                        context.Request.Params["txtQuestionNum"], context.Request.Params["txtQuestionFen"]
                        );

					 o_model.PaperInfo = o_model.MarkInfo;



					using (var ctx= _ctx)
					{
						ctx.PaperInfo.RemoveRange(ctx.PaperInfo.Where(s=>s.PaperId==o_model.PaperID));
						  
                       // ctx.Entry(o_model).State = System.Data.Entity.EntityState.Modified;
						//ctx.PaperInfo.AddRange(o_model.PaperInfo);
						ctx.SaveChanges();
					}

					context.Response.Write(editId);//修改成功，返回ID
					#endregion
					break;
                case "del":
                    #region 删除
                    using (var ctx=new Data.OnlineExamEntities())
                    {
                        if (ctx.Score.Any(s => s.PaperID == ID))
                        {
                            context.Response.Write("已经有用户成绩,不能删除");
                        }
                        ctx.SingleProblem.RemoveRange(ctx.SingleProblem.Where(s => s.PaperID == ID));
                        ctx.MultiProblem.RemoveRange(ctx.MultiProblem.Where(s => s.PaperID == ID));
                        ctx.JudgeProblem.RemoveRange(ctx.JudgeProblem.Where(s => s.PaperID == ID));
                        ctx.FillBlankProblem.RemoveRange(ctx.FillBlankProblem.Where(s => s.PaperID == ID));
                        ctx.QuestionProblem.RemoveRange(ctx.QuestionProblem.Where(s => s.PaperID == ID));

                        ctx.PaperInfo.RemoveRange( ctx.PaperInfo.Where(s=>s.PaperId==ID));
                        ctx.Paper.Remove(ctx.Paper.FirstOrDefault(s=>s.PaperID==ID));
                        ctx.SaveChanges();
                        context.Response.Write(ID);//删除成功，返回ID

                    }
                    
                    #endregion
                    break;
                default:
                    break;
            }
        }
		private void WriteJson(object data)
		{
			_httpResponse.Write(data.SerializeObject());
			_httpResponse.End();
		}
		public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}